package com.winai.launcher.view;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.ks.projectbasictools.utils.JSONUtil;
import com.winai.launcher.R;
import com.winai.launcher.base.BaseActivity;
import com.winai.launcher.bean.responseEntity.CityEntity;
import com.winai.launcher.override.ClearTextEditText;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.builder.PostFormBuilder;
import com.zhy.http.okhttp.callback.StringCallback;
import com.zhy.http.okhttp.request.RequestCall;
import com.zhy.view.flowlayout.FlowLayout;
import com.zhy.view.flowlayout.TagAdapter;
import com.zhy.view.flowlayout.TagFlowLayout;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * 作者：康少
 * 时间：2020/6/8 0008
 * 说明：天气二级页面——城市定位
 */
public class LocationActivity extends BaseActivity {

    @BindView(R.id.str_title)
    TextView strTitle;
    @BindView(R.id.et_input)
    ClearTextEditText etInput;
    @BindView(R.id.tfl_list)
    TagFlowLayout tflList;
    @BindView(R.id.tv_empty)
    TextView tvEmpty;

    private Context mContext = this;
    private final String HeWeatherKey = "d93805d91f62488dbf60b65722b2dd7e";
    private final String HeHotCityKey = "52b7a2157b4c4a0a8cfd14fb9c8ddf6a";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_location);
        ButterKnife.bind(this);
        start();
    }

    private void start() {
        initObject();
        requestData(null);
        initListener();
    }

    private void initObject() {
        strTitle.setText("");
    }

    private void initListener() {
        etInput.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                requestData(s.toString());
            }
        });
    }

    private void requestData(final String keyword) {
        String url;
        if (TextUtils.isEmpty(keyword)) {
            url = "https://search.heweather.net/top";
        } else {
            url = "https://search.heweather.net/find";
        }
        RequestCall requestCall;
        PostFormBuilder postFormBuilder;

        postFormBuilder = OkHttpUtils.post()
                .url(url);
        postFormBuilder.addParams("group", "cn");
        if (!TextUtils.isEmpty(keyword)) {
            postFormBuilder.addParams("number", "14");
            postFormBuilder.addParams("location", keyword);
            postFormBuilder.addParams("key", HeHotCityKey);
        } else {
            postFormBuilder.addParams("key", HeWeatherKey);
        }
        requestCall = postFormBuilder
                .tag(mContext)
                .build();
        requestCall.execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                //没有更多城市了
                tvEmpty.setVisibility(!TextUtils.isEmpty(keyword) ? View.VISIBLE : View.GONE);
            }

            @Override
            public void onResponse(String response, int id) {
                String[] heWeather6s = JSONUtil.getStringArray(response, "HeWeather6", null);
                List<CityEntity.HeWeather6Bean.BasicBean> statusLs = new ArrayList<>();
                Gson gson = new Gson();
                if (heWeather6s != null && heWeather6s.length > 0) {
                    for (int i = 0; i < heWeather6s.length; i++) {
                        String[] basics = JSONUtil.getStringArray(heWeather6s[i], "basic", null);
                        if (basics != null && basics.length > 0) {
                            for (int j = 0; j < basics.length; j++) {
                                statusLs.add(gson.fromJson(basics[j]
                                        , new TypeToken<CityEntity.HeWeather6Bean.BasicBean>() {
                                        }.getType()));
                            }
                        }
                    }
                }
                addCityTag(keyword, statusLs);
                //没有更多城市了
                tvEmpty.setVisibility(!TextUtils.isEmpty(keyword) ? View.VISIBLE : View.GONE);
            }
        });
    }

    private void addCityTag(final String keyword, List<CityEntity.HeWeather6Bean.BasicBean> statusLs) {
        TagAdapter<CityEntity.HeWeather6Bean.BasicBean> adapter = new TagAdapter<CityEntity.HeWeather6Bean.BasicBean>(statusLs) {
            @SuppressLint("SetTextI18n")
            @Override
            public View getView(FlowLayout parent, int position, CityEntity.HeWeather6Bean.BasicBean bean) {
                View inflate = LayoutInflater.from(mContext).inflate(R.layout.item_city, parent, false);
                TextView tvCity = inflate.findViewById(R.id.tv_city);
                TextView tvFirst = inflate.findViewById(R.id.tv_first);
                if (!TextUtils.isEmpty(keyword)) {
                    tvFirst.setVisibility(View.GONE);
                    tvCity.setVisibility(View.VISIBLE);
                } else {
                    tvFirst.setVisibility(position == 0 ? View.VISIBLE : View.GONE);
                    tvCity.setVisibility(position == 0 ? View.GONE : View.VISIBLE);
                }
                if (bean.getParent_city().equals(bean.getLocation())) {
                    tvCity.setText(bean.getLocation());
                } else {
                    tvCity.setText(bean.getParent_city() + "-" + bean.getLocation());
                }
                return inflate;
            }
        };
        tflList.setAdapter(adapter);
        /*
         * Tag标签点击事件
         */
        tflList.setOnTagClickListener(new TagFlowLayout.OnTagClickListener() {
            @Override
            public boolean onTagClick(View view, int position, FlowLayout parent) {
                if (position == 0 && TextUtils.isEmpty(etInput.getText())) {
                    // 获取当前定位城市
                    Intent intent = new Intent();
                    intent.putExtra("locationCurrent", true);
                    setResult(Activity.RESULT_OK, intent);
                    finish();
                } else {
                    // 回调选中的城市
                    Intent intent = new Intent();
                    intent.putExtra("locationCurrent", false);
                    intent.putExtra("BasicBean", statusLs.get(position));
                    setResult(Activity.RESULT_OK, intent);
                    finish();
                }
                return false;
            }
        });
    }

    @OnClick({R.id.iv_back, R.id.iv_home, R.id.tv_cancel})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.iv_home:
                //模拟HOME
                Intent intent = new Intent(Intent.ACTION_MAIN);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.addCategory(Intent.CATEGORY_HOME);
                mContext.startActivity(intent);
                break;
            case R.id.tv_cancel:
                etInput.setText("");
                break;
        }
    }
}
